package com.kay.server;

import com.kay.mapper.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Description: 将 InputStream 输入流，封装成 Request 对象
 * @Author: Kay
 * @CreateDate: 2021/8/3$ 10:18$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/8/3$ 10:18$
 */
public class Request {
    private String method;
    private String url;
    private InputStream inputStream;
    private MapperData mapperData;

    public MapperData getMapperData() {
        return mapperData;
    }

    public void setMapperData(MapperData mapperData) {
        this.mapperData = mapperData;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Request(InputStream inputStream, Mapper mapper) throws IOException {
        this.inputStream = inputStream;
        int count = 0;
        while (count == 0) {
            try {
                count = inputStream.available();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);
        String request = new String(bytes);
        String firstLine = request.split("\\n")[0]; // GET /index HTTP/1.1   http://localhost:8888/index
        String[] split = firstLine.split(" ");
        this.method = split[0];
        this.url = split[1];
        this.mapperData = setMapperDataByUrl(url, mapper);
    }

    /**
     * 根据URL 获取对应的MapperData
     * @param url
     * @param mapper
     */
    private  MapperData setMapperDataByUrl(String url, Mapper mapper) { // demo1/demo
        MapperData mapperData =  new MapperData();
        List<Host> hostList = mapper.getHostList();
        for (Host host : hostList) {
            List<Context> contextList = host.getObject();
            for (Context context : contextList) {
                String webName = "/" + context.getName(); // demo1
                if (url.startsWith(webName)) {
                    mapperData.host = host;
                    mapperData.context = context;
                    url = url.replaceFirst(webName, "");
                }
                List<Wrapper> wrapperList = context.getObject();
                for (Wrapper wrapper : wrapperList) {
                    if (wrapper.getName().equals(url)) {
                        mapperData.wrapper = wrapper;
                        return mapperData;
                    }
                }
            }
        }
        return mapperData;
    }
}
